package org.osami.gateway.mediator.drools.sender;

import org.osami.gateway.type.Luminosity;
import org.osami.gateway.type.Temperature;
import org.osgi.service.log.LogService;
import org.ow2.jasmine.rules.api.IDroolsWorkingMemory;
import org.ow2.jasmine.rules.api.IDroolsWorkingMemoryPool;

import fr.liglab.adele.cilia.Data;
import fr.liglab.adele.cilia.framework.ISender;

public class DroolsSender implements ISender {

	// TODO replace with a global variable.
	private static final String GATEWAY_ID = "B1-163";

	private final String DEFAULT_MEMORY_NAME = "default";

	private final String AVERAGE_VALUE_KEY = "average-value";

	private final String AVERAGE_TYPE_KEY = "average-type";
	
	private final String AVERAGE_LOCATION_KEY = "average-location";
	/**
	 * Drools Service, injected by iPOJO.
	 */
	private IDroolsWorkingMemory droolmem;

	/**
	 * Logger, injected by iPOJO.
	 */
	private LogService logger;

	/**
	 * Extract type information from SenseData object and Add the appropriate
	 * object to the drools working memory.
	 */
	public boolean send(Data data) {

		boolean res = false;
		// Add the Temperature average to the Drools memory
		try {
			if (data != null) {
				String type = (String) data.getProperty(AVERAGE_TYPE_KEY);
				if (type != null) {
					Double average = (Double) data.getProperty(AVERAGE_VALUE_KEY);
					if (average != null) {
						String location = (String) data.getProperty(AVERAGE_LOCATION_KEY);
						String ext="";
						if ("temperature".equals(type)) {
							
							Temperature temperature = new Temperature(average,GATEWAY_ID,location);
							ext=droolmem.insert(temperature).toExternalForm();
							res = true;
						}
						if ("luminosity".equals(type)) {
							Luminosity luminosity = new Luminosity(average,GATEWAY_ID,location);
							ext=droolmem.insert(luminosity).toExternalForm();
							res = true;
						}
						logger.log(LogService.LOG_INFO,"Average "+type+" injected to drools, val: "+average+" Result= "+ext);
					} else {
						logger.log(LogService.LOG_WARNING,"Average info is null, ignoring data");
					}
				} else {
					logger.log(LogService.LOG_WARNING,"Type info is null, ignoring data");
				}
			} else {
				logger.log(LogService.LOG_WARNING,"Data gathered by sender is null");
			}
		} catch (Exception e) {
			logger.log(LogService.LOG_ERROR, e.getMessage());
		}
		return res;
	}

	private void bindDroolsMemoryPool(IDroolsWorkingMemoryPool pool) {
		droolmem = pool.get(DEFAULT_MEMORY_NAME);

		if (droolmem == null) {
			throw new RuntimeException("The DroolsWorkingMemory "
					+ DEFAULT_MEMORY_NAME + "cannot be found ! mediator down ");
		}
	}

	private void stop() {
		droolmem = null;
	}

}
